package com.example.demo.pdf.Controller;

import com.example.demo.pdf.MyHeaderFooter;
import com.example.demo.pdf.PdfService;
import com.example.demo.pdf.Watermark;
import com.example.demo.pdf.service.PdfService2;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author zjq
 * @date 2022/1/13 - 17:01
 */
@RestController
@RequestMapping("/api/pdf")
@Api(value = "自定义PDFcontroller", tags = {"自定义PDF生成"})
public class PdfController {
    //这个controller是单个pdf的下载
    @Resource
    private PdfService pdfService;

    @Autowired
    private PdfService2 pdfService2;

    @ApiOperation(value = "生成pdf并下载，有临时文件产生")
    @GetMapping("downloadOdf")
    public void downloadFailedUsingJson(HttpServletRequest req, HttpServletResponse response) {
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            File file = new File("demo" + ".pdf");
            file.createNewFile();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setPageEvent(new Watermark("Zhejiang Quzhou No.1 Middle School"));// 水印 ---只支持英文
            writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("Title@PDF-Java");// 标题
            document.addAuthor("Author@umiz");// 作者
            document.addSubject("Subject@iText pdf sample");// 主题
            document.addKeywords("Keywords@iTextpdf");// 关键字
            document.addCreator("Creator@umiz`s");// 创建者

            // 4.向文档中添加内容
            pdfService.generatePDF(document);

            // 5.关闭文档
            document.close();

            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 设置response的Header
            String fileName = "demo";
            String fileNameURL = java.net.URLEncoder.encode(fileName + ".pdf", "UTF-8");
            response.setHeader("content-disposition",
                    "attachment;filename=" + fileNameURL + ";" + "filename*=utf-8''" + fileNameURL);
            response.setContentType("application/pdf");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @ApiOperation(value = "生成pdf下载，没有临时文件产生")
    @GetMapping("downloadOdf2")
    public void downloadFailedUsingJson1(HttpServletRequest req, HttpServletResponse response) {
        try {
            // 1.新建document对象
            Document document = new Document(PageSize.A4);// 建立一个Document对象

            // 2.建立一个书写器(Writer)与document对象关联
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            PdfWriter writer = PdfWriter.getInstance(document, out);
            writer.setPageEvent(new Watermark("Zhejiang Quzhou No.1 Middle School"));// 水印 ---只支持英文
            writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            // 3.打开文档
            document.open();
            document.addTitle("Title@PDF-Java");// 标题
            document.addAuthor("Author@umiz");// 作者
            document.addSubject("Subject@iText pdf sample");// 主题
            document.addKeywords("Keywords@iTextpdf");// 关键字
            document.addCreator("Creator@umiz`s");// 创建者

            // 4.向文档中添加内容
            pdfService.generatePDF(document);

            // 5.关闭文档
            document.close();

            // 设置response的Header
            String fileName = "demo";
            String fileNameURL = java.net.URLEncoder.encode(fileName + ".pdf", "UTF-8");
            response.setHeader("content-disposition",
                    "attachment;filename=" + fileNameURL + ";" + "filename*=utf-8''" + fileNameURL);
            response.setContentType("application/pdf");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(out.toByteArray());
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @ApiOperation(value = "根据模板填充pdf文件，利用流，会占用内存，此方法适用单个文件")
    @GetMapping("downloadpdf")
    public void downloadFai(HttpServletRequest req, HttpServletResponse response) {
        pdfService2.fillPdf(req, response);
    }
}
